﻿using ARchGL.Declaration.Platform.Domain.Entities;
using log4net;
using System;
using System.Linq;
using System.Threading;
using System.Web;
using TDF.Core.Exceptions;
using TDF.Core.Ioc;
using TDF.Core.Log;
using TDF.Core.Operator;
using TDF.Data.Repository;

namespace ARchGL.Declaration.Platform.Service
{
    /// <summary>
    /// 基础服务
    /// </summary>
    public class BaseService
    {
        /// <summary>
        /// 日志
        /// </summary>
        public ILog Log => LogFactory.GetLogger(GetType());

        /// <summary>
        /// 初始化 Token
        /// </summary>
        /// <param name="token"></param>
        public void InitLoginToken(string token)
        {
            if (string.IsNullOrWhiteSpace(token?.Trim())) throw new KnownException("登录状态过期，请退出重新登录");
            LoginToken = token.Trim();

            CurrentSession = GetSessionByToken(LoginToken);
            if (CurrentSession == null) throw new KnownException("登录状态过期，请退出重新登录");

            if (DateTime.Now > CurrentSession.ExpiredTime) throw new KnownException("登录状态过期，请退出重新登录");
        }

        /// <summary>
        /// 登录 Token
        /// </summary>
        public string LoginToken { get; set; }

        /// <summary>
        /// 登录信息
        /// </summary>
        public Sys_Session CurrentSession { get; set; }
               
        /// <summary>
        /// 创建操作记录
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="dataId"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        public void CreateOperatorHistory(OperatorEntityBase dto, Guid dataId, OperatorType type, string remark)
        {
            var thread = new Thread(() =>
            {
                try
                {
                    using (var repository = Ioc.Resolve<IRepositoryBase<OperatorHistory>>())
                    {
                        var entity = dto.Merge<OperatorEntityBase, OperatorHistory>();
                        entity.Id = Guid.NewGuid();
                        entity.DataId = dataId;
                        entity.Type = type;
                        entity.Remark = remark;
                        entity.AccountId = CurrentSession.AccountId;
                        entity.AccountName = CurrentSession.AccountName;
                        repository.Insert(entity);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("保存操作记录异常：", ex);
                }
            })
            { IsBackground = true };
            thread.Start();
        }

        /// <summary>
        /// 根据登录 Token 获取登录帐号信息
        /// </summary>
        /// <param name="token">登录 Token</param>
        /// <returns></returns>
        private Sys_Session GetSessionByToken(string token)
        {
            using (var repository = Ioc.Resolve<IRepositoryBase<Sys_Session>>())
            {
                var entity = repository.FindEntity(x => x.Token == token.Trim() && x.ExpiredTime > DateTime.Now);
                UpdateSession(entity);
                return entity;
            }
        }

        /// <summary>
        /// 更新 Session 延长过期时间
        /// </summary>
        /// <param name="entity"></param>
        private void UpdateSession(Sys_Session entity)
        {
            if (entity.IsNull()) return;
            var thread = new Thread(() =>
            {
                try
                {
                    using (var repository = Ioc.Resolve<IRepositoryBase<Sys_Session>>())
                    {
                        entity.ExpiredTime = DateTime.Now.AddDays(7);
                        repository.Update(entity);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("延长 Session 过期时间异常：", ex);
                }
            })
            { IsBackground = true };
            thread.Start();
        }
    }
}
